package cn.tedu.sp06.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.jnlp.FileContents;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
@Component
public class AccessFilter extends ZuulFilter {

//设置过滤类型
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
//位置序号
    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        //对指定的serviceid过滤，如果要过滤所有服务，直接返回true
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        if(serviceId.equals("item-service")){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/txssdaad?token=teseads
        //获得request对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        //如果没有token阻止访问，如果有继续访问
        if(StringUtils.isBlank(token)){
            //阻止继续访问
            ctx.setSendZuulResponse(false);
            //直接返回响应
            ctx.addZuulResponseHeader("ContentType","text/html;charset=UTF-8");
            ctx.setResponseBody("Not Login!");
        }

        return null;
    }
}
